<template>
	<div class="coupon-data">
		<head-back-title title="优惠券详情"></head-back-title>
		<el-card>
			<el-form :model="couponForm" ref="couponForm" :rules="couponFormRules" label-width="120px">
				<el-row><div class="title">优惠券基本信息</div></el-row>
				<el-row>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="优惠卷名称:" prop="coupon_name"><el-input v-model="couponForm.coupon_name" placeholder="请输入优惠卷名称"></el-input></el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="满减金额:" prop="satisfy_money"><el-input v-model="couponForm.satisfy_money" placeholder="(满足的金额要求)"></el-input></el-form-item>
					</el-col>
						<el-col :xs="18" :sm="10" :lg="5" v-if="couponForm.type == 1">
							<el-form-item label="优惠卷的金额:" prop="money"><el-input v-model="couponForm.money" placeholder="（实际减少的金额）"></el-input></el-form-item>
						</el-col>
						<el-col :xs="18" :sm="10" :lg="5" v-if="couponForm.type == 2">
							<el-form-item label="折扣:" prop="discount"><el-input v-model="couponForm.discount" placeholder="请输入折扣"></el-input></el-form-item>
						</el-col>
				</el-row>

				<el-row>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="获取途径 :" prop="style">
							<el-select v-model="couponForm.style" placeholder="请选择">
								<el-option label="新用户赠送" value="1"></el-option>
								<el-option label="活动" value="2"></el-option>
								<el-option label="买会员送" value="3"></el-option>
								<el-option label="续费" value="4"></el-option>
								<el-option label="赠送" value="5"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="优惠卷类型:" prop="type">
							<el-select v-model="couponForm.type" placeholder="请选择" @change="typeSelect">
								<el-option label="满减" value="1"></el-option>
								<el-option label="打折" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="备注:" prop="remark"><el-input v-model="couponForm.remark" placeholder="请输入备注"></el-input></el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="C端/B端:" prop="use_type">
							<el-select v-model="couponForm.use_type" placeholder="请选择">
								<el-option label="C端普通用户优惠券" value="1"></el-option>
								<el-option label="B端商家优惠券（平台发行）" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="状态:" prop="status">
							<el-select v-model="couponForm.status" placeholder="请选择">
								<el-option label="上架" value="1"></el-option>
								<el-option label="下架" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="使用场景:" prop="use_scenarios">
							<el-select v-model="couponForm.use_scenarios" placeholder="请选择">
								<el-option label="线上" :value="0"></el-option>
								<el-option label="线下" :value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="定制类型:" prop="customized_type">
							<el-select v-model="couponForm.customized_type" placeholder="请选择">
								<el-option label="家具大师" :value="0"></el-option>
								<el-option label="家配大师" :value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="开始时间:" prop="begin_time">
							<el-date-picker
							v-model="couponForm.begin_time"
							type="datetime"
							format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
							default-time="00:00:00"
							placeholder="选择过期时间">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="10" :lg="5">
						<el-form-item label="过期时间:" prop="stop_time">
							<el-date-picker
							v-model="couponForm.stop_time"
							type="datetime"
							format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
							default-time="23:59:59"
							placeholder="选择过期时间">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="上传图片:" class="upload-box" prop="image">
							<div class="case-img-upload">
								<div class="case-img-upload-btns">
									<el-upload ref="upload" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload(res); } " multipleaccept="image/*" :on-change="onchange" > <el-button type="primary" size="small">上传图片</el-button>
									</el-upload>
									<el-button type="danger" size="small" @click="rest">重置</el-button>
									<div class="el-upload__tip">小于1MB</div>
								</div>
								<div class="case-img-upload-imgs-info">
									<el-image v-if="!image.length"><div slot="error"></div></el-image>
									<div class="vice_big_box" v-else><el-image :src="image" fit="contain"></el-image></div>
								</div>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="使用规则:">
							<quill-editor class="ql-editor" ref="myQuillEditor" v-model="couponForm.content" :options="editorOption"></quill-editor>
						</el-form-item>
					</el-col>
				</el-row>
				<el-button type="primary" @click="submitForm('couponForm')" style="margin-left: 40px;" v-if="this.$route.query.isAdd == 1">添加</el-button>
				<el-button type="primary" @click="submitForm('couponForm')" style="margin-left: 40px;" v-else>修改</el-button>
			</el-form>
		</el-card>
	</div>
</template>

<script>
	import md5 from 'md5'
	import 'quill/dist/quill.core.css'; // import styles
	import 'quill/dist/quill.snow.css'; // for snow theme
	import 'quill/dist/quill.bubble.css'; // for bubble theme
	import {
		quillEditor,
		Quill
	} from 'vue-quill-editor';
	import {
		container,
		addQuillTitle
	} from 'quill-video-image-module';
	import {
		ImageExtend,
		QuillWatch
	} from 'quill-video-image-module';
	import {
		VideoExtend,
		QuillVideoWatch
	} from 'quill-video-image-module';
	// 引入video模块并注册
	import video from 'quill-video-image-module/video';
	Quill.register(video, true);

	Quill.register('modules/ImageExtend', ImageExtend);
	Quill.register('modules/VideoExtend', VideoExtend);
export default {
	components:{
		quillEditor
	},
	data() {
		return {
			image: '',
			couponForm: {
				coupon_name: '',
				satisfy_money: '',
				money: '',
				style: '',
				icon: '',
				type: '1',
				discount: '',
				remark: '',
				status: '',
				use_type: '',
				customized_type:0,
				use_scenarios:0,
				stop_time:"",
				content:"",
				begin_time:""
			},
			couponFormRules: {
				coupon_name: [{ required: true, message: '请输入优惠卷名称' }],
				satisfy_money: [{ required: true, message: '请输入满减金额' }],
				money: [{ required: true, message: '请输入内容' }],
				style: [{ required: true, message: '请选择获取途径' }],
				type: [{ required: true, message: '请选择优惠券类型' }],
				discount: [{ required: true, message: '请输入折扣' }],
				status: [{ required: true, message: '请选择状态' }],
				use_type: [{ required: true, message: '请选择C端/B端' }],
				icon: [{ required: true, message: '请上传优惠券背景图' }],
				customized_type: [{ required: true, message: '请选择定制类型' }],
				use_scenarios: [{ required: true, message: '请选择使用场景' }],
				stop_time: [{ required: true, message: '请选择过期时间' }]
			},
			// 富文本框参数设置
			editorOption: {
				modules: {
					ImageExtend: {
						loading: true, // 可选参数 是否显示上传进度和提示语
						name: 'file[]', // 图片参数名
						size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
						action: `${this.$domain}api/Upimg/UpImg`, // 服务器地址, 如果action为空，则采用base64插入图片
						// response 为一个函数用来获取服务器返回的具体图片地址
						// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
						// 则 return res.data.url
						response: res => {
							return res.datas[0];
						},
						headers: () => {}, // 可选参数 设置请求头部
						start: () => {}, // 可选参数 自定义开始上传触发事件
						end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
						error: () => {}, // 可选参数 自定义网络错误触发的事件
						change: (xhr, formData) => {
							formData.append('timestamp', Math.round(new Date() * 1000));
							formData.append('port', 'pc');
							formData.append('sign', this.getSign());
							formData.append('key', localStorage.getItem('token'));
						}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
						sizeError: () => {
							this.$message({
								message: '图片不能大于1M',
								type: 'warning'
							});
						}
					},
					VideoExtend: {
						loading: true,
						name: 'file[]',
						size: 100, // 可选参数 视频大小，单位为M，1M = 1024kb
						action: `${this.$domain}api/Upimg/UpVideo`, // 视频上传接口
						headers: xhr => {
							// set custom token(optional)
						},
						response: res => {
							// video uploaded path
							// custom your own
							return res.datas;
						},
						change: (xhr, formData) => {
							formData.append('timestamp', Math.round(new Date() * 1000));
							formData.append('port', 'pc');
							formData.append('sign', this.getSign());
							formData.append('key', localStorage.getItem('token'));
						}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
						sizeError: () => {
							this.$message({
								message: '视频不能大于100M',
								type: 'warning'
							});
						}
					},
					toolbar: {
						container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
						handlers: {
							image: function() {
								// 劫持原来的图片点击按钮事件
								QuillWatch.emit(this.quill.id);
							},
							video: function() {
								QuillVideoWatch.emit(this.quill.id);
							}
						}
					}
				}
			}
		};
	},
	methods: {
		// 图片上传
		upload(params) {
			//console.log(params);
			const file = params.file,
				isJPGPNG = file.type === 'image/jpeg' || 'image/png',
				isLt1MB = file.size / 1024 <= 1024;
			if (!isJPGPNG) {
				this.$message.error('只能上传图片格式png、jpg!');
				return;
			}
			if (!isLt1MB) {
				this.$message.error('图片不能大于1M');
				return;
			}

			this.couponForm.icon = new FormData();
			this.couponForm.icon.append('file[]', file);
		},
		onchange(file, fileList) {
			let isJPGPNG = file.raw.type === 'image/jpeg' || 'image/png',
				isLt1MB = file.size / 1024 <= 1024;
			if (!isJPGPNG) {
				return;
			}
			if (!isLt1MB) {
				return;
			}

			var event = event || window.event;
			var file = event.target.files[0];
			var reader = new FileReader();
			//转base64
			reader.onload = e => {
				this.image = e.target.result; //将图片路径赋值给src
			};
			reader.readAsDataURL(file);
		},

		// 重置图片
		rest() {
			this.image = '';
			this.couponForm.icon = '';
		},
		//提交
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					if (this.$route.query.isAdd == 0) {
						delete this.couponForm.add_time;
						delete this.couponForm.store_id;
						if (this.image == this.couponForm.icon) {
							this.$http(this.$ApiList.CardEdit, this.couponForm).then(res => {
								this.$layer.msg('修改成功');
								this.$router.push('/coupon_list');
							});
						} else {
							this.$http(this.$ApiList.publicUpload, this.couponForm.icon).then(res => {
								this.couponForm.icon = res.datas[0];
								this.$http(this.$ApiList.CardEdit, this.couponForm).then(res => {
										this.$layer.msg('修改成功');
										this.$router.push('/coupon_list');
								});
							});
						}
					} else {
						this.$http(this.$ApiList.publicUpload, this.couponForm.icon).then(res => {
							this.couponForm.icon = res.datas[0];
							this.$http(this.$ApiList.CardAdd, this.couponForm).then(res => {
									this.$layer.msg('添加成功');
									this.$router.push('/coupon_list');
							});
						});
					}
				} else {
					this.$layer.msg('请填写完整信息后提交');
				}
			});
		},
		getDetails(id) {
			let data = {
				coupon_id: id
			};
			this.$http(this.$ApiList.CardInfo, data).then(res => {
				this.couponForm = res.datas;
				this.couponForm.type = String(res.datas.type);
				this.couponForm.use_type = String(res.datas.use_type);
				this.couponForm.status = String(res.datas.status);
				this.image = res.datas.icon;
				this.couponForm.stop_time = this.couponForm.stop_time == 0 ?'':this.couponForm.stop_time;
			});
		},
		typeSelect(){
			if(this.couponForm.type == 1){
				this.couponFormRules = {
					coupon_name: [{ required: true, message: '请输入优惠卷名称' }],
					satisfy_money: [{ required: true, message: '请输入满减金额' }],
					money: [{ required: true, message: '请输入内容' }],
					style: [{ required: true, message: '请选择获取途径' }],
					type: [{ required: true, message: '请选择优惠券类型' }],
					status: [{ required: true, message: '请选择状态' }],
					use_type: [{ required: true, message: '请选择C端/B端' }],
					icon: [{ required: true, message: '请上传优惠券背景图' }]
				}
			}else if(this.couponForm.type == 2){
				this.couponFormRules = {
					coupon_name: [{ required: true, message: '请输入优惠卷名称' }],
					satisfy_money: [{ required: true, message: '请输入满减金额' }],
					style: [{ required: true, message: '请选择获取途径' }],
					type: [{ required: true, message: '请选择优惠券类型' }],
					discount: [{ required: true, message: '请输入内容' }],
					status: [{ required: true, message: '请选择状态' }],
					use_type: [{ required: true, message: '请选择C端/B端' }],
					icon: [{ required: true, message: '请上传优惠券背景图' }]
				}
			}
		},
		getSign() {
			let data = {
				key: localStorage.getItem('token'),
				timestamp: Math.round(new Date() * 1000),
				port: 'pc'
			}
			// 获取签名开始
			let obj = 'jjds2020+'
			let newObj = this.objKeySort(data)
			for (let i in newObj) {
				obj += i + '=' + newObj[i] + '&'
			}
			obj = obj.substring(0, obj.length - 1)
			obj += '+jjds2020'
			obj = md5(obj)
			return obj
		},
		// 参数排序
		objKeySort(obj) {
			var newkey = Object.keys(obj).sort();
			var newObj = {};
			for (var i = 0; i < newkey.length; i++) {
				newObj[newkey[i]] = obj[newkey[i]];
			}
			return newObj;
		},
	},
	created() {
		if (this.$route.query.isAdd == 0) {
			this.getDetails(this.$route.query.id);
		}
	}
};
</script>
<style lang="scss">
.coupon-data {
	.last {
		margin-bottom: 0;
	}
	.upload-drag {
		.el-upload {
			vertical-align: top;
		}
		.el-upload__tip {
			line-height: normal;
		}
	}
	.case_upload {
		display: flex;
		flex-wrap: wrap;
		.el-col {
		}
	}
	.el-select {
		display: block;
	}
	.upload-box {
		padding-left: 40px;
		.case-img-upload {
			display: flex;
			.case-img-upload-imgs {
				flex: 1;
				align-items: flex-start;
				.el-image {
					width: 140px;
					height: 140px;
					border: solid 1px #e5e5e5;
					margin-left: 25px;
					vertical-align: top;
				}
			}
			.case-img-upload-imgs-info {
				min-width: 296px;
				max-width: 660px;
				border: solid 1px #e5e5e5;
				margin-left: 25px;
				min-height: 296px;
				.case-img-upload-imgs-info-box {
					position: relative;
					.el-icon-error {
						position: absolute;
						font-size: 20px;
						color: #ef3030;
						right: 5px;
						top: 5px;
						z-index: 1;
						background-color: #fff;
						border-radius: 50%;
						cursor: pointer;
					}
				}
				.el-image {
					width: 100%;
					vertical-align: top;
				}
			}
			.vice_big_box {
				position: relative;
				display: inline-block;
				vertical-align: top;
				.el-icon-error {
					position: absolute;
					font-size: 20px;
					color: #ef3030;
					right: 5px;
					top: 5px;
					z-index: 1;
					background-color: #fff;
					border-radius: 50%;
					cursor: pointer;
				}
			}
		}
		.el-upload__tip {
			width: 80px;
			text-align: center;
		}
		.el-form-item__label {
			float: none;
		}
		.el-form-item__content {
			margin-left: 0 !important;
			.el-button--danger {
				width: 80px;
				background-color: #37c1d6;
				border-color: #37c1d6;
			}
		}
	}
	.ql-container .ql-editor {
		height: 400px;
		img {
			width: 300px;
		}
	}
}
</style>
